# -*- coding: utf-8 -*-
import pygame
from PIL import Image
import os
import os.path as osp
import shutil


BASEDIR = osp.dirname(osp.abspath(__file__))
OUTDIR = osp.join(BASEDIR, 'coordinates_outdir')
if not osp.exists(OUTDIR):
    os.makedirs(OUTDIR)


def click_to_record_coordinations(path_canvas):
    canvas_name = osp.basename(path_canvas)   
         
    # 背景图原始大小
    orig_bg_img = Image.open(path_canvas).convert("RGB")
    orig_img_w, orig_img_h = orig_bg_img.size

    # 缩放至的尺寸
    img_w, img_h = 640, 640
    
    # 缩小倍数
    scale_w, scale_h = orig_img_w / img_w, orig_img_h / img_h
    
    # ============= 启动pygame
    pygame.init()

    # 设置屏幕大小
    screen = pygame.display.set_mode((img_w, img_h))
    pygame.display.set_caption(f"Recording Clicked Coordinates for {canvas_name}")

    # 背景图
    bg_img = pygame.image.load(path_canvas)
    bg_img = pygame.transform.scale(bg_img, (img_w, img_h)).convert()

    # 物体图
    path_plane_img = osp.join(BASEDIR, 'icons', 'plane.png')
    plane_img = pygame.image.load(path_plane_img)
    plane_img = pygame.transform.scale(plane_img, (32, 32)).convert()

    # 肖像图
    # path_portrait_img = osp.join(BASEDIR, 'icons', 'portrait.jpg')
    # portrait_img = pygame.image.load(path_portrait_img)
    # portrait_img = pygame.transform.scale(portrait_img, (64, 64)).convert()

    points_record = []

    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                points_record_str = '\n'.join(list(map(str, points_record))) \
                + f'\n\nscale_w:{scale_w}, scale_h:{scale_h}\n' \
                + f'this_w:{img_w}, this_h:{img_h}\n' \
                + f'original_w:{orig_img_w}, original_h:{orig_img_h}\n'
                path_outlog = osp.join(OUTDIR, f"{canvas_name.split('.')[-2]}.txt")
                with open(path_outlog, 'w') as fp:
                    fp.write(points_record_str)
                return
            
            if event.type == pygame.MOUSEBUTTONDOWN:
                x, y = pygame.mouse.get_pos()
                print(x, y)
                points_record.append([x, y])
                
        # 展示背景图
        screen.blit(bg_img, (0, 0))
        # 展示肖像图
        # screen.blit(portrait_img, (img_w/2 - 32, img_h - 64))
        # 获取鼠标位置
        x, y = pygame.mouse.get_pos()
        # 计算飞机的左上角位置
        x -= plane_img.get_width() / 2
        y -= plane_img.get_height() / 2
        # 把飞机显到屏幕上
        screen.blit(plane_img, (x, y))
        # 更新屏幕
        pygame.display.update()


if __name__ == '__main__':
    canvas_folder = osp.abspath(osp.join(BASEDIR, 'canvas_lib'))
    imgnames = [name for name in os.listdir(canvas_folder) if name.split('.')[-1] in ('png', 'jpg', 'bmp', 'tif')]
    for imgname in imgnames:
        path_canvas = osp.join(canvas_folder, imgname)
        click_to_record_coordinations(path_canvas)
